﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Net.Sockets;
using IPMsgExpections;
using CommonUtility;

namespace IPMSG
{
    internal class SocketChatClient
    {
        //地址与端口号
        private IPEndPoint ipEP;

        //连接Socket
        private Socket tcpClient;

        private StateObject stateObj;

        //获取或设置地址与端口号
        internal IPEndPoint IpEP
        {
            get { return ipEP; }
            set { ipEP = value; }
        }

        //获取或者设置连接Socket
        internal Socket TcpClient
        {
            get { return tcpClient; }
            set { tcpClient = value; }
        }

        /*
        //主动连接到对方主机
        internal void ActiveConnect()
        {
            Socket connecter = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            connecter.BeginConnect(this.ipEP as EndPoint, new AsyncCallback(this.OnActiveConnectRequest), connecter);
        }

        //异步处理主动连接
        private void OnActiveConnectRequest(IAsyncResult ar)
        {
            Socket connecter = ar.AsyncState as Socket;

            try
            {
                //结束异步连接请求
                connecter.EndConnect(ar);
                this.tcpClient = connecter;
                this.SetReceiveCallBack();
            }
            catch (SocketException socketEx)
            {
                throw new NetExpection(socketEx.Message, socketEx);
            }
            catch (Exception ex)
            {
                throw new IPmsgExpection(ex.Message, ex);
            }
        }

        /// <summary>
        /// 开始接受数据,无论主动连接还是被动连接，最终都转到这里
        /// </summary>
        internal void SetReceiveCallBack()
        {
            //包含缓冲区信息和缓冲区大小
            stateObj = new StateObject();
            tcpClient.BeginReceive(stateObj.buffer, 0, StateObject.BufferSize, SocketFlags.None, new AsyncCallback(this.GetReceiveData), tcpClient);
        }

        /// <summary>
        /// 异步接收数据
        /// </summary>
        /// <param name="ar">异步状态</param>
        private void GetReceiveData(IAsyncResult ar)
        {
            Socket connecter = (Socket)ar.AsyncState;

            try
            {
                //获取接受字节数
                int count = connecter.EndReceive(ar);

                if (count > 0)
                {
                    byte[] receivedBuffer = stateObj.buffer;

                    //回调，继续接收
                    this.SetReceiveCallBack();

                    //处理收到的当前buffer
                    this.HandleMessage(receivedBuffer);
                }
                else
                {
                    Log.Info(string.Format("TCP - {0} disconnected!", connecter.RemoteEndPoint));
                    if (connecter.Connected)
                    {
                        connecter.Shutdown(SocketShutdown.Both);
                    }

                    connecter.Close();
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex.Message);
            }
        }
        /*/
        internal virtual void HandleMessage(byte[] buffer)
        {
        }
    }

    internal class StateObject
    {
        internal const int BufferSize = 1024;
        internal byte[] buffer = new byte[BufferSize];
    }
}
